﻿using System.Diagnostics;
using ConsoleApp;
using IdentityModel.Client;
using Microsoft.AspNetCore.SignalR.Client;


Console.WriteLine("Api启动后按回车......");
Console.ReadLine();

var p = new myProg(); 
var loginResult =  await p.SignIn();
myProg.ShowResult(loginResult);
var currentAccessToken = loginResult.AccessToken;
var user = loginResult.User.Identity.Name;

Console.WriteLine("认证测试完成，按回车继续......");
Console.ReadLine();

var apiClient = new HttpClient();
apiClient.SetBearerToken(currentAccessToken);
var response = await apiClient.GetAsync(
    "http://host.docker.internal:5189/api/Game/GetPlayerByUserName?name="+user);
if (!response.IsSuccessStatusCode)
{
    Console.WriteLine(response.StatusCode);
    Console.WriteLine(await response.Content.ReadAsStringAsync());
}
else
{
    var content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}

Console.ReadLine();

var connection = new HubConnectionBuilder()
    .WithUrl("http://host.docker.internal:5189/singlegamehub", options =>
    {
        options.AccessTokenProvider = () => Task.FromResult(currentAccessToken);
    })
    .Build();

connection.Closed += async (error) =>
{
    await Task.Delay(new Random().Next(0, 5) * 1000);
    await connection.StartAsync();
};

connection.On<string>("PlayerExist", (user) =>
{
    Console.WriteLine("玩家存在:" + user);
});

connection.On<string>("PlayerNotExist", (user) =>
{
    Console.WriteLine("玩家不存在:" + user);
});

try
{
    await connection.StartAsync();
    await connection.InvokeAsync("CheckUser", user);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
Console.ReadLine();